import { defineStore } from 'pinia';
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '@/api/category';

export const useCategoryStore = defineStore('category', {
  state: () => ({
    categoryList: [],
    total: 0,
  }),
  actions: {
    async getCategoryList(pageNum = 1, pageSize = 10) {
      try {
        const res : any = await getCategoryList({ pageNum, pageSize });
        this.categoryList = res.records;
        this.total = res.total;
        return res;
      } catch (error) {
        console.error('获取分类列表失败:', error);
        return [];
      }
    },
    async addCategory(category: { name: string; description: string }) {
      try {
        await addCategory(category);
        return true;
      } catch (error) {
        console.error('添加分类失败:', error);
        return false;
      }
    },
    async updateCategory(category: { id: number | null; name: string; description: string }) {
      try {
        if (category.id) {
          await updateCategory(category.id, category);
          return true;
        }
        return false;
      } catch (error) {
        console.error('更新分类失败:', error);
        return false;
      }
    },
    async deleteCategory(id: number) {
      try {
        await deleteCategory(id);
        return true;
      } catch (error) {
        console.error('删除分类失败:', error);
        return false;
      }
    }
  }
}); 